package viv.karaoke.book;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.ActionBar;
import android.app.ActionBar.OnNavigationListener;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.ActionMode;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.SearchView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.SearchView.OnQueryTextListener;
import android.widget.Toast;

public class MainActivity extends Activity implements OnGestureListener 
{
	private static final int SWIPE_MIN_DISTANCE = 120;
    private static final int SWIPE_MAX_OFF_PATH = 250;
    private static final int SWIPE_THRESHOLD_VELOCITY = 200;
    private GestureDetector gestureDetector;
    View.OnTouchListener gestureListener;
    
    private Menu mainMenu;
    
	public Menu getMainMenu() {
		return mainMenu;
	}

	private MenuItem mSpinnerItem = null;
	
	private user currentProfile;
	
	public user getCurrentProfile() {
		return currentProfile;
	}

	public void setCurrentProfile(user currentProfile) {
		this.currentProfile = currentProfile;
	}

	public SearchView mSearchView;
	public String mQuery = "";

	private SongDataSource datasource;
	
	private int brightnessValue;
		
	public int getBrightnessValue() {
		return brightnessValue;
	}

	public void setBrightnessValue(int brightnessValue) {
		this.brightnessValue = brightnessValue;
	}
	
	private int idleTime;

	public int getIdleTime() {
		return idleTime;
	}

	public void setIdleTime(int idleTime) {
		this.idleTime = idleTime;
	}

	private class MyTabListener implements ActionBar.TabListener
	{
		private Fragment mFragment;
		private final Activity mActivity;
		private final String mFragName;
		

		public MyTabListener( Activity activity, String fragName )
		{
			mActivity = activity;
			mFragName = fragName;
		}

		@Override
		public void onTabReselected( Tab tab, FragmentTransaction ft )
		{
			// TODO Auto-generated method stub
			if (mFragment == null) {
				
				mFragment = Fragment.instantiate( mActivity, mFragName );
				ft.add( android.R.id.content, mFragment );
			}
			else
			{
				ft.replace(android.R.id.content, mFragment);
			}
					
		}

		@Override
		public void onTabSelected( Tab tab, FragmentTransaction ft )
		{
			mFragment = Fragment.instantiate( mActivity, mFragName );
			ft.add( android.R.id.content, mFragment );
		}

		@Override
		public void onTabUnselected( Tab tab, FragmentTransaction ft )
		{
			ft.remove( mFragment );
			mFragment = null;
		}
	}

	private ActionMode.Callback mCallback = new ActionMode.Callback()
	{
		private Fragment settingFragment;
		
		@Override
		public boolean onPrepareActionMode( ActionMode mode, Menu menu )
		{
			return false;
		}

		@Override
		public void onDestroyActionMode( ActionMode mode )
		{
			// TODO Auto-generated method stub
			Activity currentActivity = settingFragment.getActivity();
			
			FragmentTransaction transaction = getFragmentManager().beginTransaction();
			transaction.remove(settingFragment);
			settingFragment = null;
			transaction.commit();
					        
			currentActivity.getActionBar().setSelectedNavigationItem(0);
		}

		@Override
		public boolean onCreateActionMode( ActionMode mode, Menu menu )
		{
			MenuInflater inflater = mode.getMenuInflater();
			inflater.inflate( R.menu.actionmode, menu );
			MenuItem item = menu.findItem( R.id.action_text );
			View v = item.getActionView();
			if( v instanceof TextView )
			{
				((TextView)v).setText( R.string.setting_title);
			}
			
			settingFragment = new SettingFragment();
			FragmentTransaction transaction = getFragmentManager().beginTransaction();
//			getFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
//			getFragmentManager().findFragmentById(id)findFragmentByTag(tag)
			
			transaction.replace(android.R.id.content, settingFragment);
		    transaction.addToBackStack(null);
		    transaction.show(settingFragment);
		    transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
		    transaction.commit();
		    
			return true;
		}

		@Override
		public boolean onActionItemClicked( ActionMode mode, MenuItem item )
		{
			boolean ret = false;
			if(item.getItemId() == R.id.actionmode_cancel) {
				mode.finish();
				
				ret = true;
			}
			
			return ret;
		}
	};

	@Override
	public void onCreate( Bundle savedInstanceState )
	{
		super.onCreate( savedInstanceState );

		// set default profile
		userDataSource userDS = new userDataSource(this);
		userDS.open();
		
		currentProfile = userDS.getFromUserId(1);
		
		userDS.close();
				
		// set default brightness
		WindowManager.LayoutParams lp = getWindow().getAttributes(); 
		lp.screenBrightness = (float) ((Constant.DEFAULT_BRIGHTNESS + 1) * 0.1); 
		getWindow().setAttributes(lp);
		
		setBrightnessValue(Constant.DEFAULT_BRIGHTNESS);
		setIdleTime(Constant.DEFAULT_IDLE_TIME);
  	    
		int mode = ActionBar.NAVIGATION_MODE_TABS;

		if (savedInstanceState != null)
		{
			mode = savedInstanceState.getInt( "mode",
					ActionBar.NAVIGATION_MODE_TABS );
		}
		ActionBar ab = getActionBar();
		ab.setDisplayShowTitleEnabled( false );
		if (mode == ActionBar.NAVIGATION_MODE_TABS)
		{
			setTabNavigation( ab );
		} else
		{
			setListNavigation( ab );
		}
		
		// Gesture detection
        gestureDetector = new GestureDetector(this, new MyGestureDetector());
//        gestureListener = new View.OnTouchListener() {
//            public boolean onTouch(View v, MotionEvent event) {
//                return gestureDetector.onTouchEvent(event);
//            }
//        };
	}

	@Override
	public boolean onTouchEvent(MotionEvent me) {
	return gestureDetector.onTouchEvent(me);
	}
    
	@Override
	protected void onSaveInstanceState( Bundle outState )
	{
		outState.putInt( "mode", getActionBar().getNavigationMode() );
		super.onSaveInstanceState( outState );
	}

	@Override
	public boolean onPrepareOptionsMenu (Menu menu)
	{
		MenuItem profileName = menu.findItem(R.id.menu_profile_name);
		profileName.setTitle("Profile Name: " + getCurrentProfile().getUserId() );
		return true;
	}
	
	@Override
	public boolean onCreateOptionsMenu( Menu menu )
	{
		getMenuInflater().inflate( R.menu.main, menu );
		mSpinnerItem = menu.findItem( R.id.menu_spinner );
		setupSpinner( mSpinnerItem );

		mainMenu = menu;
		
		// handle Search
		mSearchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();        
		
		mSearchView.setOnQueryTextListener(new OnQueryTextListener() {
			
			@Override
			public boolean onQueryTextSubmit(String query) {
				mSearchView.clearFocus();
				mQuery = query;
			    			    
				return false;
			}
			
			@Override
			public boolean onQueryTextChange(String newText) {
				
				try
				{
					mQuery = newText;
					Fragment newFragment = new SongFragment();
				    FragmentTransaction transaction = getFragmentManager().beginTransaction();
				    transaction.replace(android.R.id.content, newFragment);
				    transaction.addToBackStack(null);
				    transaction.commit();
				}
				catch(Exception ex)
				{
				}
				
				return false;
			}
		});
		
		return true;
	}

	@Override
	public boolean onOptionsItemSelected( MenuItem item )
	{
		boolean ret;
		if (item.getItemId() == R.id.menu_about)
		{
			// Handle Settings
			ret = true;
		} else if (item.getItemId() == R.id.menu_toggle)
		{
			ActionBar ab = getActionBar();
			if (ab.getNavigationMode() == ActionBar.NAVIGATION_MODE_TABS)
			{
				setListNavigation( ab );
//				mSearchItem.setVisible( false );
			} else
			{
				setTabNavigation( ab );
//				mSearchItem.setVisible( true );
			}
			ret = true;
		} else if( item.getItemId() == R.id.menu_settings)
		{
			startActionMode( mCallback );
			
			ret = true;
		} else
		{
			ret = super.onOptionsItemSelected( item );
		}
		return ret;
	}

	private void setTabNavigation( ActionBar actionBar )
	{
		actionBar.removeAllTabs();
		actionBar.setNavigationMode( ActionBar.NAVIGATION_MODE_TABS );
		actionBar.setTitle( R.string.app_name );

		Tab tab = actionBar
				.newTab()
				.setText( R.string.Songs )
				.setTabListener(
						new MyTabListener( this, SongFragment.class.getName() ) );
		actionBar.addTab( tab );

		tab = actionBar
				.newTab()
				.setText( R.string.Favourite )
				.setTabListener(
						new MyTabListener( this, FavouriteFragment.class.getName() ) );
		actionBar.addTab( tab );
		if (mSpinnerItem != null)
		{
			mSpinnerItem.setVisible( false );
		}
	}

	private void setListNavigation( ActionBar actionBar )
	{
		actionBar.setNavigationMode( ActionBar.NAVIGATION_MODE_LIST );

		final List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put( "title", getString( R.string.Songs ) );
		map.put( "fragment",
				Fragment.instantiate( this, SongFragment.class.getName() ) );
		data.add( map );
		map = new HashMap<String, Object>();
		map.put( "title", getString( R.string.Favourite ) );
		map.put( "fragment",
				Fragment.instantiate( this, FavouriteFragment.class.getName() ) );
		data.add( map );
		SimpleAdapter adapter = new SimpleAdapter( this, data,
				android.R.layout.simple_spinner_dropdown_item,
				new String[] { "title" }, new int[] { android.R.id.text1 } );
		actionBar.setListNavigationCallbacks( adapter,
				new OnNavigationListener()
				{
					@Override
					public boolean onNavigationItemSelected( int itemPosition,
							long itemId )
					{
						Map<String, Object> map = data.get( itemPosition );
						Object o = map.get( "fragment" );
						if (o instanceof Fragment)
						{
							FragmentTransaction tx = getFragmentManager()
									.beginTransaction();
							tx.replace( android.R.id.content, (Fragment) o );
							tx.commit();
						}
						return true;
					}
				} );
		if (mSpinnerItem != null)
		{
			setupSpinner( mSpinnerItem );
		}
	}

	private void setupSpinner( MenuItem item )
	{
		item.setVisible( getActionBar().getNavigationMode() == ActionBar.NAVIGATION_MODE_LIST );
		View view = item.getActionView();
		if (view instanceof Spinner)
		{
			Spinner spinner = (Spinner) view;
			spinner.setAdapter( ArrayAdapter.createFromResource( this,
					R.array.spinner_data,
					android.R.layout.simple_spinner_dropdown_item ) );
		}
	}

	/*
	@Override
	public void onBackPressed() {
	    // Do Here what ever you want do on back press;
	}
	*/
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	     if (keyCode == KeyEvent.KEYCODE_BACK) {
	     //preventing default implementation previous to android.os.Build.VERSION_CODES.ECLAIR
	     return true;
	     }
	     return super.onKeyDown(keyCode, event);    
	}

	class MyGestureDetector extends SimpleOnGestureListener {
		  
	    @Override
	    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
	        try {
	            if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
	                return false;
	            // right to left swipe
	            if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
	                Toast.makeText(MainActivity.this, "Left Swipe", Toast.LENGTH_SHORT).show();
	            }  else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
	                Toast.makeText(MainActivity.this, "Right Swipe", Toast.LENGTH_SHORT).show();
	            }
	        } catch (Exception e) {
	            // nothing
	        }
	        return false;
	    }

	}

	@Override
	public boolean onDown(MotionEvent arg0) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
		// TODO Auto-generated method stub
		try {
            if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
                return false;
            // right to left swipe
            if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                Toast.makeText(MainActivity.this, "Left Swipe", Toast.LENGTH_SHORT).show();
            }  else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                Toast.makeText(MainActivity.this, "Right Swipe", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            // nothing
        }
        return false;
	}

	@Override
	public void onLongPress(MotionEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean onScroll(MotionEvent arg0, MotionEvent arg1, float arg2,
			float arg3) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onShowPress(MotionEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean onSingleTapUp(MotionEvent arg0) {
		// TODO Auto-generated method stub
		return false;
	}

	
}


